package com.stanwind.sgit.exec;

import com.stanwind.sgit.util.ShellUtil;
import java.io.IOException;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ReadStreamThread
 * 读取console输出线程
 *
 * @author : Stan
 * @version : 1.0
 * @date :  2019-11-30 18:58
 **/
public class ReadStreamThread extends Thread {

    private static final Logger logger = LoggerFactory.getLogger(ReadStreamThread.class);
    private InputStream inputStream;
    private StringBuilder sb;

    public ReadStreamThread(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String getMsg() {
        return sb.toString();
    }

    @Override
    public void run() {
        sb = new StringBuilder();
        this.setName("READ_LOG");
        logger.info("exec log thread start");
        while (true) {
            try {
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    String temp = new String(buffer, 0, len, ShellUtil.SHELL_CHARSET);
                    sb.append(temp);
                    logger.info("exec log:" + temp);
                }

                sleep(500);
            } catch (IOException e) {
                logger.info("read error", e);
            } catch (InterruptedException e) {
                logger.info("read sleep error", e);
            }
        }
    }
}
